<?php

namespace App\Jobs;

use App\Models\User;
use DB;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Config;

class CustomMail extends ConfigurableMailable {
	use Queueable, SerializesModels;

	public $config;
	public $subject;
	public $content;
    public $type;
	/**
	 * Create a new message instance.
	 *
	 * @return void
	 */
	public function __construct( $user, $subject, $content,$type) {
		// 这里是传给父类的参数
		$this->subject = $subject;
		$this->content = $content;
		$this->type = $type;
		$userInfo = $user;
		if($type==1){
            $userInfo->company_id = $userInfo->appcompany_id;
        }
        \Log::info('44'.json_encode($userInfo));
		$mailInfo = DB::table('email_sets')
			->where('company_id', $userInfo->company_id)
			->first();
		if (!empty($mailInfo) && $mailInfo->type == 1) {
			$encryption = '';
		} else if (!empty($mailInfo) && $mailInfo->type == 2) {
			$encryption = 'ssl';
		} else if (!empty($mailInfo) && $mailInfo->type == 3) {
			$encryption = 'tls';
		}
		//var_dump($mailInfo);
		\Log::info('邮件配置' . json_encode($mailInfo));
		$host = $mailInfo->host ?? 'smtp.mailgun.org';
		$port = $mailInfo->port ?? '587';
		$username = $mailInfo->user_name ?? '';
		$password = $mailInfo->password ?? '';
		$address = $mailInfo->address ?? 'hello@example.com';
		$name = $mailInfo->name ?? '罗姆网络';
		Config::set('mail.encryption', $encryption);
		Config::set('mail.host', $host);
		Config::set('mail.port', $port);
		Config::set('mail.username', $username);
		Config::set('mail.password', $password);
		Config::set('mail.from', ['address' => $address, 'name' => $name]);
        \Log::info('ADDRESS' . $address);
		$info['username'] = $username;
		$info['password'] = $password;
		$info['from'] = $address;
		$info['name'] = $name;
		$this->config = $info;
	}

	/**
	 * Build the message.
	 *
	 * @return $this
	 */
	public function build() {
		\Log::info('邮件开始发送');
		// 发送邮件
		return $this->from($this->config['from'], $this->config['name'])->subject($this->subject)->view('emails.test');
	}
}